package org.wzl.service.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.wzl.service.service.CacheService;
import org.wzl.service.utils.JsonWrapUtil;

import java.util.concurrent.TimeUnit;

/**
 * @author: 卫志龙
 * @date: 2024年06月29日 19:21
 */
@Service
public class CacheServiceImpl implements CacheService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void set(String key, Object value, long expire, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, JsonWrapUtil.toJsonString(value), expire, timeUnit);
    }

    public <T> T get(String key, TypeReference<T> typeReference) {
        return JsonWrapUtil.toObject((String) redisTemplate.opsForValue().get(key),
                typeReference);
    }

    @Override
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public Boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public boolean setIfAbsent(String key, Object value, long expire, TimeUnit timeUnit) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit));
    }

}
